﻿#region using
using System;
using CoreApi.Meta;
using Common.Tools;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Common.Data;
using System.Collections.Generic;
using System.Collections;
using System.Data;
using System.Data.Common;
using System.Transactions;
using System.Configuration;
#endregion

namespace CoreApi.Impl
{
    public class DataCollect:IDataCollect
    {
        private IThresholder _thresholder;
        private string _conName = "daq";
        public DataCollect(IThresholder thresholder)
        {
            this._thresholder = thresholder;
            this._conName = ConfigurationManager.AppSettings["daq.connectionStringName"] ?? _conName;
        }
        private void CreateAlarm(Database db, DbTransaction trans, string citizenId, string accountId,string type,DateTime measureTime, float measureValue, int sbp, int dbp, string attribute,string description)
        {
            DbColumn[] columns = new DbColumn[]{
                new DbColumn("AlarmId",IdHelper.GetGuid())
                ,new DbColumn("CitizenId",citizenId)
                ,new DbColumn("AccountId",accountId)
                ,new DbColumn("Type",type)
                ,new DbColumn("MeasureTime",DbType.DateTime,measureTime)
                ,new DbColumn("MeasureValue",DbType.Single,measureValue)
                ,new DbColumn("Sbp",DbType.Int32,sbp)
                ,new DbColumn("Dbp",DbType.Int32,dbp)
                ,new DbColumn("Attribute",attribute)
                ,new DbColumn("Status",AlarmStatus.Open)
                ,new DbColumn("AlarmTime",DbType.DateTime,DateTime.Now)
                ,new DbColumn("Description",description)
            };
            DbHelper.ExecuteInsert(db, trans, SQL.TABLE.ACCOUNTALARM, columns);
        }

        #region IDataCollect implementation
        public ReturnValue CollectBloodPressureMeasureData(BloodPressureMeasureData data)
        {
            if (data.BrandId == null || data.BrandId.Equals(String.Empty) || data.DeviceSN == null || data.DeviceSN.Equals(string.Empty) || data.Dbp == 0 || data.Sbp == 0) return new ReturnValue(false, ErrorMessage.DataCollect.MissingKeyValue);
            Database db = DatabaseFactory.CreateDatabase(_conName);
            List<DbFilter> filters=new List<DbFilter>();
            filters.Add(new DbFilter("c.DeviceSN",data.DeviceSN));
            filters.Add(new DbFilter("c.BrandId",data.BrandId));
            if (data.DataNumber != null && !data.DataNumber.Equals(string.Empty)) filters.Add(new DbFilter("b.DataNumber", data.DataNumber));
            IDictionary dt=DbHelper.ExecuteSingle(db, null, SQL.DataCollect.FindCitizen, filters.ToArray());
            if (dt == null) return new ReturnValue(false, ErrorMessage.DataCollect.NotFoundBindedData);
            string citizenId = dt["CITIZENID"].ToString();
            string accountId = dt["ACCOUNTID"].ToString();
            string gender = dt["GENDER"].ToString();
            int age=DateTime.Now.Year-int.Parse(dt["BIRTHDAYYEAR"].ToString());
            DbColumn[] columns = new DbColumn[]{
                new DbColumn("DataId",IdHelper.GetGuid())
                ,new DbColumn("CitizenId",citizenId)
                ,new DbColumn("BrandId",data.BrandId)
                ,new DbColumn("DeviceSN",data.DeviceSN)
                ,new DbColumn("DataNumber",data.DataNumber??"")
                ,new DbColumn("MeasureTime",DbType.DateTime,data.MeasureTime)
                ,new DbColumn("Sbp",DbType.Int32,data.Sbp)
                ,new DbColumn("Dbp",DbType.Int32,data.Dbp)
                ,new DbColumn("Attribute",data.Attribute)
            };
            using (TransactionScope tx = new TransactionScope())
            {
                int rds = DbHelper.ExecuteInsert(db, null, SQL.TABLE.BLOODPRESSURE, columns);
                ReturnValue bpCheck = _thresholder.BPIsHealth(gender, age, data.Sbp, data.Dbp);
                if (rds > 0 && !bpCheck.Passed) CreateAlarm(db, null, citizenId, accountId, AlarmType.BloodPressure, data.MeasureTime, 0.0f, data.Sbp, data.Dbp, data.Attribute,bpCheck.Data.ToString());
                tx.Complete();
            }
            return new ReturnValue();
        }
        public ReturnValue CollectGlycemicMeasureData(GlycemicMeasureData data)
        {
            if (data.BrandId == null || data.BrandId.Equals(String.Empty) || data.DeviceSN == null || data.DeviceSN.Equals(string.Empty) || data.MeasureValue == 0) return new ReturnValue(false, ErrorMessage.DataCollect.MissingKeyValue);
            Database db = DatabaseFactory.CreateDatabase(_conName);
            List<DbFilter> filters = new List<DbFilter>();
            filters.Add(new DbFilter("c.DeviceSN", data.DeviceSN));
            filters.Add(new DbFilter("c.BrandId", data.BrandId));
            if (data.DataNumber != null && !data.DataNumber.Equals(string.Empty)) filters.Add(new DbFilter("b.DataNumber", data.DataNumber));
            IDictionary dt = DbHelper.ExecuteSingle(db, null, SQL.DataCollect.FindCitizen, filters.ToArray());
            if (dt == null) return new ReturnValue(false, ErrorMessage.DataCollect.NotFoundBindedData);
            string citizenId = dt["CITIZENID"].ToString();
            string accountId = dt["ACCOUNTID"].ToString();
            string DataId = IdHelper.GetGuid();
            DbColumn[] columns = new DbColumn[]{
                new DbColumn("DataId",DataId)
                ,new DbColumn("CitizenId",citizenId)
                ,new DbColumn("BrandId",data.BrandId)
                ,new DbColumn("DeviceSN",data.DeviceSN)
                ,new DbColumn("DataNumber",data.DataNumber??"")
                ,new DbColumn("MeasureTime",DbType.DateTime,data.MeasureTime)
                ,new DbColumn("MeasureValue",DbType.Single,data.MeasureValue)
                ,new DbColumn("Meal",data.Meal)
                ,new DbColumn("Attribute",data.Attribute)
            };
            using (TransactionScope tx = new TransactionScope())
            {
                int rds = DbHelper.ExecuteInsert(db, null, SQL.TABLE.GLYCEMIC, columns);
                ReturnValue rv=_thresholder.GlycemicIsHealth(data.Meal,data.MeasureValue);
                if (rds > 0 && !rv.Passed) CreateAlarm(db, null, citizenId, accountId, AlarmType.Glycemic, data.MeasureTime,data.MeasureValue,0, 0 ,data.Meal,rv.Data.ToString());
                tx.Complete();
            }
            return new ReturnValue();
        }
        private ReturnValue CollectAlarmSignal(AlarmSignal data,string alarmType)
        {
            if (data.BrandId == null || data.BrandId.Equals(String.Empty) || data.DeviceSN == null || data.DeviceSN.Equals(string.Empty)) return new ReturnValue(false, ErrorMessage.DataCollect.MissingKeyValue);
            Database db = DatabaseFactory.CreateDatabase(_conName);
            List<DbFilter> filters = new List<DbFilter>();
            filters.Add(new DbFilter("b.DeviceSN", data.DeviceSN));
            filters.Add(new DbFilter("b.BrandId", data.BrandId));
            if (data.DataNumber != null && !data.DataNumber.Equals(string.Empty)) filters.Add(new DbFilter("a.DataNumber", data.DataNumber));
            IDictionary dt = DbHelper.ExecuteSingle(db, null, SQL.DataCollect.FindAccount, filters.ToArray());
            if (dt == null) return new ReturnValue(false, ErrorMessage.DataCollect.NotFoundBindedData);
            string accountId = dt["ACCOUNTID"].ToString();
            DbColumn[] columns = new DbColumn[]{
                new DbColumn("AlarmId",IdHelper.GetGuid())
                ,new DbColumn("AccountId",accountId)
                ,new DbColumn("BrandId",data.BrandId)
                ,new DbColumn("DeviceSN",data.DeviceSN)
                ,new DbColumn("DataNumber",data.DataNumber??"")
                ,new DbColumn("MeasureTime",DbType.DateTime,data.MeasureTime)
                ,new DbColumn("Attribute",data.Attribute)
                ,new DbColumn("Testing",DbType.Boolean,data.Testing)
            };
            using (TransactionScope tx = new TransactionScope())
            {
                string tb = alarmType.Equals(AlarmType.GasAlarm) ? SQL.TABLE.GASALARM : SQL.TABLE.SMOKEALARM;
                int rds = DbHelper.ExecuteInsert(db, null,tb, columns);
                if (rds > 0 && !data.Testing) CreateAlarm(db, null, null, accountId, alarmType, data.MeasureTime, 0, 0, 0, data.Attribute, "");
                tx.Complete();
            }
            return new ReturnValue();
        }
        public ReturnValue CollectSmokeAlarmSignal(AlarmSignal data)
        {
            return CollectAlarmSignal(data, AlarmType.SmokeAlarm);
        }
        public ReturnValue CollectGasAlarmSignal(AlarmSignal data)
        {
            return CollectAlarmSignal(data, AlarmType.GasAlarm);
        }

        #endregion
    
    }
}
